/**
 * org.assess.core.service.BaseServiceImpl
 */
package org.assess.core.service;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.assess.core.bean.BaseEntry;
import org.assess.core.bean.BaseTbEntry;
import org.assess.core.bean.UserSession;
import org.assess.core.common.Constants;
import org.assess.core.common.DateUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.opensymphony.xwork2.ActionContext;

/**
 * @description 基础Service实现类
 * @author XiaLongxiang
 * @createtime 2012-5-17 下午2:06:29
 */
public class BaseServiceImpl {
    public String toListPageString(int page, int rows, int totalrecords, String idMethodName,
            List<? extends BaseEntry> records) {
        StringBuffer result = new StringBuffer();
        
        int totalpages = 1;
        if(rows != -1) {
            totalpages = totalrecords / rows;
            totalpages += (totalrecords == 0 || (totalrecords % rows > 0)) ? 1 : 0;
        }
        
        if (StringUtils.isNotBlank(idMethodName) && records != null && !records.isEmpty()
                && (records.get(0) instanceof BaseTbEntry)) {
            try {
                Method method = records.get(0).getClass().getMethod(idMethodName);
                for (BaseEntry entry : records) {
                    String idValue = (String) method.invoke(entry);
                    ((BaseTbEntry) entry).setId(idValue);
                }
            }
            catch (Exception e) {
            }
        }
        
        SerializeConfig config = new SerializeConfig();
        config.put(Date.class, new SimpleDateFormatSerializer(DateUtils.STYLE_DEFAULT));
        
        result.append("{\"totalpages\":\"").append(totalpages).append("\",");
        result.append("\"currpage\":\"").append(page).append("\",");
        result.append("\"totalrecords\":\"").append(totalrecords).append("\",");
        result.append("\"results\":").append(JSON.toJSONString(records, config)).append("}");
        return result.toString();
    }
    
    public String toCheckExistsString(boolean isExists) {
        return "{\"success\":\"true\",\"isExists\":\"" + isExists + "\"}";
    }
    
    public String toResultString(boolean result) {
        return "{\"success\":\"" + result + "\"}";
    }
    
    public String getLoginUserCode() {
        UserSession userSession = (UserSession) ActionContext.getContext().getSession().get(Constants.G_USER_SESSION);
        
        return userSession != null ? userSession.getUserCode() : "admin";
    }
    
}
